package org.ru.mse10.cvis.web.validator;

import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.html.HtmlInputSecret;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.apache.commons.lang.StringUtils;

/**
 * The Class EqualPasswordValidator.
 */
@FacesValidator(value = "equalPasswordsValidator")
public class EqualPasswordValidator implements Validator {

	/** The context. */
	private final FacesContext context = FacesContext.getCurrentInstance();

	/** The bundle. */
	private final ResourceBundle bundle = context.getApplication()
			.getResourceBundle(context, "message");

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.faces.validator.Validator#validate(javax.faces.context.FacesContext
	 * , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		UIInput password = (UIInput) component.getAttributes().get(
				"passwordFiled");

		String passwordValue = (String) password.getValue();
		String confirmPassword = (String) value;

		if (!StringUtils.isEmpty(passwordValue)) {
			if (passwordValue.length() < 6 || passwordValue.length() > 20
					|| StringUtils.isEmpty(confirmPassword)
					|| confirmPassword.length() < 6
					|| confirmPassword.length() > 20) {
				throw new ValidatorException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR,
						bundle.getString("notEnoughLength"), null));
			}
			if (!passwordValue.equals(confirmPassword)) {
				throw new ValidatorException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR,
						bundle.getString("notMatchPasswords"), null));
			}
			((HtmlInputSecret) component).setSubmittedValue("");
			((HtmlInputSecret) password).setSubmittedValue("");
		}
	}
}
